import { MenuResponse } from "@/services/api/user";
import { createSlice } from "@reduxjs/toolkit";

export interface AuthStateType {
  token: string | null;
  username: string | null;
  menuList: MenuResponse[];
}

const INITSTATE: AuthStateType = {
  token: sessionStorage.getItem("token") || null,
  username: sessionStorage.getItem("username") || null,
  menuList: [],
};

export const authSlice = createSlice({
  name: "auth",
  initialState: INITSTATE,
  reducers: {
    setToken: (state, action) => {
      const { token, username } = action.payload;
      state.token = token;
      state.username = username;
      sessionStorage.setItem("token", token);
      sessionStorage.setItem("username", username);
    },
    setMenu:(state, action) => {
      const menuList = action.payload;
      state.menuList = menuList;
    },
    clearAuth: (state) => {
      state.menuList = [];
      state.username = null;
      state.token = null;
      sessionStorage.removeItem("token");
      sessionStorage.removeItem("username");
    },
  },
});

export const { setToken, clearAuth, setMenu } = authSlice.actions;
export default authSlice.reducer;
